﻿using Microsoft.VisualBasic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastGPT_Admin.Service
{
    internal class UsersService
    {
        private readonly IMongoCollection<Users> _collection;

        public UsersService(string connectionString, string databaseName, string collectionName)
        {
            // 创建MongoClient
            var client = new MongoClient(connectionString);
            // 获取数据库
            IMongoDatabase database = client.GetDatabase(databaseName);
            // 获取集合
            _collection = database.GetCollection<Users>(collectionName);
        }

        // 创建（Create）
        public ObjectId Create(Users model)
        {
            _collection.InsertOne(model);
            return model.Id;
        }

        // 读取（Read）
        public List<Users> Read(string usernameValue = "")
        {
            if (String.IsNullOrEmpty(usernameValue))
            {
                var filter = _collection.Find(new BsonDocument()).ToList();
                return filter;
            } else
            {
                // var filter = Builders<Users>.Filter.Eq(m => m.Username, usernameValue);
                // 使用正则表达式进行模糊匹配
                var filter = Builders<Users>.Filter.Regex(m => m.Username, new BsonRegularExpression($".*{usernameValue}.*", "i"));
                return _collection.Find(filter).ToList();
            }
        }

        // 更新（Update）
        public bool Update(string propertyIdValue, Users updatedModel)
        {
            var filter = Builders<Users>.Filter.Eq(m => m.Id, ObjectId.Parse(propertyIdValue));
            var update = Builders<Users>.Update
                .Set(m => m.Username, updatedModel.Username)
                .Set(m => m.Status, updatedModel.Status);

            // 只有当Password不为空时，才更新Password
            if (!string.IsNullOrEmpty(updatedModel.Password))
            {
                update = update.Set(m => m.Password, updatedModel.Password);
            }

            // 执行更新操作
            var result = _collection.UpdateOne(filter, update);
            /*if (result.IsAcknowledged)
            {
                Console.WriteLine("Update operation was acknowledged.");
                Console.WriteLine("Matched Count: " + result.MatchedCount);
                Console.WriteLine("Modified Count: " + result.ModifiedCount);

                if (result.UpsertedId != null)
                {
                    Console.WriteLine("Upserted document ID: " + result.UpsertedId);
                }
            }
            else
            {
                Console.WriteLine("Update operation was not acknowledged.");
            }*/
            return result.IsAcknowledged;
        }

        // 删除（Delete）
        public void Delete(string property1Value)
        {
            // var filter = Builders<Users>.Filter.Eq(m => m.Property1, property1Value);
            // _collection.DeleteOne(filter);
        }
    }

    public class Users
    {
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("status")]
        public string? Status { get; set; }

        [BsonElement("username")]
        public string? Username { get; set; }

        [BsonElement("password")]
        public string? Password { get; set; }

        [BsonElement("avatar")]
        public string? Avatar { get; set; }

        [BsonElement("promotionRate")]
        public int PromotionRate { get; set; }

        [BsonElement("timezone")]
        public string? Timezone { get; set; }

        [BsonElement("createTime")]
        public DateTime CreateTime { get; set; }

        [BsonElement("__v")]
        public int Version { get; set; }
    }
}
